
Core.Widgets.Tree.prototype.click = function ( func ) {
    this.nodes.each( function () {
       this.customclick = func;
    });
};

Core.Widgets.Tree.prototype.hover = function ( over, out ) {
    this.nodes.each( function () {
       this.custommouseover = over;
       this.custommouseout = out;
    });
}

/**
 * Initializes the tree from existing HTML.
 *
 * @param root object DOM element that serves as the root of the tree
 */
Core.Widgets.Tree.prototype.createFrom = function ( root ) {

    var Tree = this;

    $( root ).find( "li" ).each( function () {

        var Node = new Core.Widgets.Tree.Node ();
        var a = $( this ).children( "a" ).get(0);

        Node.Element = this;
        Tree.nodes.add( Node );

        a.onclick = function () {
            if ( Node.customclick ) {
                Node.customclick();
            }
            return false;
        };
        a.onmouseover = function () {
            if ( Node.custommouseover ) {
                Node.custommouseover();
            }
        }
        a.onmouseout = function () {
            if ( Node.custommouseout ) {
                Node.custommouseout();
            }
        }

    });

    Tree.nodes.each( function () {

        var Node = this;

        if ( Node.hasChildren() ) {

            var toggleIcon;

            toggleIcon = document.createElement( "span" );
            toggleIcon.setAttribute( "class", "ToggleIcon" );
            toggleIcon.innerHTML = "q";

            Node.Element.insertBefore( toggleIcon, $( Node.Element ).children( "a" ).get(0) );

            $( toggleIcon ).click( function () {
               Node.toggle();
            });

            $( Node.Element ).children( "a" ).click( function () {

                if ( toggleIcon.innerHTML == "u" ) {

                    Node.toggle();

                }

            });

        }

    });


    $( root ).find( "li a" ).click( function () {

        $( "a.Selected" ).removeClass( "Selected" );
        $( this ).addClass( "Selected" );

    });

}

Core.Widgets.Tree.prototype.nodes = new Core.Widgets.Tree.NodeCollection ();


